<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 用户列表 -->
      <el-col>
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.name"
                placeholder="用户名/昵称/手机号"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item class="search-buttons">
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="hover" class="data-table">
          <div class="data-table__toolbar">
            <div class="data-table__toolbar--actions">
              <el-button
                v-hasPerm="['sys:user:add']"
                type="primary"
                icon="plus"
                @click="handleOpenDialog()"
              >
                新增
              </el-button>
              <!-- <el-button
                v-hasPerm="'sys:user:delete'"
                type="danger"
                icon="delete"
                :disabled="selectIds.length === 0"
                @click="handleDelete()"
              >
                删除
              </el-button> -->
            </div>
          </div>

          <el-table
            v-loading="loading"
            :data="pageData"
            border
            stripe
            highlight-current-row
            class="data-table__content"
            align="center"
            @selection-change="handleSelectionChange"
          >
            <!-- 自定义空状态 -->
            <template #empty>
              <div style="padding: 60px 0; text-align: center">
                <el-empty description="暂无数据" />
              </div>
            </template>
            <!-- <el-table-column type="selection" width="50" align="center" /> -->
            <el-table-column label="用户名" prop="username" />
            <el-table-column label="昵称" prop="name" align="center" />
            <el-table-column label="性别" width="100" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.sex === 0 || scope.row.sex === '0'" type="primary">
                  男
                </el-tag>
                <el-tag v-else type="danger">女</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="手机号码" prop="phone" align="center" />
            <el-table-column label="创建时间" align="center" prop="createTime" />
            <el-table-column label="操作" fixed="right" width="190">
              <template #default="scope">
                <el-button
                  v-hasPerm="'sys:user:passban'"
                  type="primary"
                  icon="SwitchFilled"
                  link
                  size="small"
                  @click="banAccount(scope.row.status === 1 ? 0 : 1, scope.row.id)"
                >
                  {{ scope.row.status === 1 ? "禁用" : "启用" }}
                </el-button>
                <el-button
                  v-hasPerm="'sys:user:edit'"
                  type="primary"
                  icon="edit"
                  link
                  size="small"
                  @click="handleOpenDialog(scope.row.id)"
                >
                  编辑
                </el-button>
                <el-button
                  v-hasPerm="'sys:user:delete'"
                  type="danger"
                  icon="delete"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.page"
            v-model:limit="queryParams.pageSize"
            @pagination="fetchData"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户表单 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      :size="drawerSize"
      :close-on-click-modal="false"
      @close="handleCloseDialog"
    >
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="头像" prop="avatar">
          <SingleImageUpload v-model="formData.avatar" />
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            :readonly="formData && !!formData.id"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item v-if="formData.id" label="密码" prop="password">
          <el-input v-model="formData.password" placeholder="如需修改密码则请填写" />
        </el-form-item>

        <el-form-item label="用户昵称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入用户昵称" />
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-select v-model="formData.sex" placeholder="请选择" style="width: 240px">
            <el-option label="女" value="1" />
            <el-option label="男" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>

        <el-form-item v-if="formData.id" label="状态" prop="status">
          <el-switch
            v-model="formData.status"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app-store";
import { DeviceEnum } from "@/enums/settings/device-enum";

import UserAPI from "@/api/system/user-api";
import EmployeeAPI from "@/api/system/employee";
import { useUserStore } from "@/store";
const userStore = useUserStore();
defineOptions({
  name: "User",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const userFormRef = ref();

const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: "",
});

const pageData = ref<any[]>([]);
const total = ref(0);
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: "新增用户",
});
const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));

const formData = reactive({
  username: "",
  name: "",
  phone: "",
  sex: "",
  avatar: "",
  id: null as number | null,
  password: "",
  status: 1,
});

const rules = reactive({
  username: [{ required: true, message: "员工名不能为空", trigger: "blur" }],
  name: [{ required: true, message: "员工昵称不能为空", trigger: "blur" }],
  phone: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

// 选中的用户ID
const selectIds = ref<number[]>([]);
// 导入弹窗显示状态
const importDialogVisible = ref(false);

// 获取数据
async function fetchData() {
  loading.value = true;
  try {
    const data = await EmployeeAPI.list(queryParams);
    console.log(data);
    pageData.value = data.data.records;
    total.value = data.data.total;
  } finally {
    loading.value = false;
  }
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.page = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  queryParams.name = "";
  fetchData();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

// 禁用/启用账号
async function banAccount(status: any, id: any) {
  EmployeeAPI.enableDisable({ status, id }).then(() => {
    ElMessage.success(status === 1 ? "禁用用户成功" : "启用用户成功");
    handleResetQuery();
  });
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(id?: string) {
  if (id) {
    dialog.title = "修改用户";
    EmployeeAPI.detail(id).then((data) => {
      // console.log(data.data);
      Object.assign(formData, { ...data.data });
      formData.password = "";
    });
  } else {
    dialog.title = "新增用户";
  }
  dialog.visible = true;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = null;
  Object.assign(formData, {
    username: "",
    name: "",
    phone: "",
    sex: "",
    avatar: "",
  });
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        EmployeeAPI.change(formData)
          .then(() => {
            ElMessage.success("修改用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        console.log(formData);
        EmployeeAPI.add(formData)
          .then(() => {
            ElMessage.success("新增用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**
 * 检查是否删除当前登录用户
 * @param singleId 单个删除的用户ID
 * @param selectedIds 批量删除的用户ID数组
 * @param currentUserInfo 当前用户信息
 * @returns 是否包含当前用户
 */
function isDeletingCurrentUser(
  singleId?: number | string,
  selectedIds: (number | string)[] = [],
  currentUserInfo?: any
): boolean {
  // 验证当前用户信息是否存在且有id字段
  if (!currentUserInfo || !currentUserInfo.id) {
    return false;
  }

  // 统一转为字符串进行比较，避免类型不一致导致的比较错误
  const currentUserId = String(currentUserInfo.id);

  // 单个删除检查
  if (singleId !== undefined && singleId !== null) {
    return String(singleId) === currentUserId;
  }

  // 批量删除检查
  if (selectedIds.length > 0) {
    return selectedIds.some((id) => String(id) === currentUserId);
  }

  return false;
}

/**
 * 删除用户
 *
 * @param id  用户ID
 */
function handleDelete(id?: number) {
  // 安全检查：防止删除当前登录用户
  const currentUserInfo = userStore.userInfo.data;
  if (id == currentUserInfo.id) {
    ElMessage.error("不能删除当前登录用户");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      EmployeeAPI.delEmployee(id)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
